package com.example.administrator.wallet.view.fragment.asset;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.AssetListAdapter;
import com.example.administrator.wallet.base.BaseFragment;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.GetVersionBean;
import com.example.administrator.wallet.model.bean.MainBean;
import com.example.administrator.wallet.model.bean.TokenBean;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.RecoveryActivity;
import com.example.administrator.wallet.view.activity.asset.AddCurrencyActivity;
import com.example.administrator.wallet.view.activity.asset.ReceivableActivity;
import com.example.administrator.wallet.view.activity.asset.RecordActivity;
import com.example.administrator.wallet.view.activity.mine.About.AboutActivity;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.example.administrator.wallet.view.activity.mine.Contacts.AddContactActivity.compareVersion;

/**
 * Effect:
 * <p>
 * Author:  CaiYapeng
 * <p>
 * Time  :  2018/7/12.
 */

public class AssetFragment extends BaseFragment {

    @Bind(R.id.skm)
    LinearLayout skm;
    @Bind(R.id.mList)
    ListView mList;
    @Bind(R.id.price)
    TextView price;
    @Bind(R.id.price_00)
    TextView price00;
    @Bind(R.id.ewm)
    TextView ewm;
    @Bind(R.id.refresh)
    ClassicsHeader refresh;
    @Bind(R.id.smart)
    SmartRefreshLayout smart;
    @Bind(R.id.insert)
    ImageView insert;
    @Bind(R.id.fl_activity)
    FrameLayout fl_activity;

    @Bind(R.id.ll_force_updata)
    LinearLayout ll_force_updata;
    @Bind(R.id.loadError)
    TextView loadError;
    @Bind(R.id.loading)
    ImageView loading;
    @Bind(R.id.loadText)
    TextView loadText;
    private List<MainBean.DataBean.ListBean> dataBeanList;
    public AssetListAdapter adapter;
    private MainBean mainBean;
    private String s1;
    private String s2;
    private String langage;
    private String eth_addr;
    private String eth_addrs;
    private View view;
    private Animation hyperspaceJumpAnimation;
    IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    int code = 0;
    private GetVersionBean getVersionBean;
    private List<GetVersionBean.DataBean> data1;
    int value = 0;


    @Override
    public void init() {
        loadError.setVisibility(View.GONE);
        initData();
        // 加载动画
        int i = SharedPrefsUtil.getValue(getActivity(), "wallet", "codes", 1);
        hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                getActivity(), R.anim.load_animations);
        if (i == 0) {
            loading.startAnimation(hyperspaceJumpAnimation);
        }
        // 使用ImageView显示动画
        eth_addr = SharedPrefsUtil.getValue(getActivity(), "wallet", "eth_addr", null);
        eth_addrs = SharedPrefsUtil.getValue(getActivity(), "wallet", "eth_addrs", null);
        if (eth_addr != null) {
            ewm.setText(eth_addr);
        }
        data1 = new ArrayList<>();

        if (value == 0) {
            value = 1;
            checkUpdate();
        }

    }

    private void checkUpdate() {
        //当前版本
        final String versionname = getVersionName(getContext());
        //判断是否需要更新
        reqequestManager.httpPost(Api.BaseUrl + Api.Get_Version, Api.getVersion(SharedPrefsUtil.getValue(getActivity(),"wallet", "token",""),"android",versionname), new IRequestCallback(){
            @Override
            public void onSuccess(String Response) {
                Gson gson = new Gson();
                getVersionBean = gson.fromJson(Response,GetVersionBean.class);
                code = getVersionBean.getCode();
                if (code == 200){
                    data1.addAll(getVersionBean.getData());
                    String getlowversion =data1.get(0).getVer_num();
                    String package_url = data1.get(0).getPackage_url();
                    String low_soft = data1.get(0).getLow_soft();

                    Log.e("tag!!!",low_soft  +  versionname);

                    //与最小版本比较，得出更新类型
                    int value = compareVersion(low_soft,versionname);

                    if (value  == -1 | value == 0){
                        //0代表相等，1代表version1大于version2，-1代表version1小于version2
                        //手动更新
                        checkUpgrade(package_url,1);
                    }else{
                        Log.e("tag!!!","强制更新");
                        //强制更新
                        checkUpgrade(package_url,0);
                    }

                }else if(code == 500){
                    //当前已是最新版本
                }
            }
            @Override
            public void onFailure(String error) {
            }
        });
    }


    private void OnClick() {
        adapter.getClickPst(new AssetListAdapter.OnClick() {
            @Override
            public void Click(MainBean.DataBean.ListBean dataBean) {
                Intent intent = new Intent(getActivity(), RecordActivity.class);
                intent.putExtra("datas", dataBean);
                getActivity().startActivity(intent);
            }
        });

        smart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (refreshlayout.isRefreshing()) {
                    initData();
                }
            }
        });

        smart.setOnLoadmoreListener(null);
        smart.setLoadmoreFinished(true);
    }

    private void initData() {
        dataBeanList = new ArrayList<>();
        IRequestManager reqequestManager = RequestFactory.getReqequestManager();
        String token = SharedPrefsUtil.getValue(getActivity(), "wallet", "token", null);
        Log.e("TAG", token);
        reqequestManager.httpPost(Api.BaseUrl + Api.Main_List, Api.getMainList(token, ""), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Log.e("TAG-MianBeanData", Response);
                Gson gson = new Gson();
                mainBean = gson.fromJson(Response, MainBean.class);
                if (mainBean.getCode() == 200) {
                    mList.setVisibility(View.VISIBLE);
                    loadError.setVisibility(View.GONE);
                    dataBeanList.clear();
                    if (mainBean.getData().getList() != null) {
                        dataBeanList.addAll(mainBean.getData().getList());
                        initAdapter();
                        loading.clearAnimation();
                        loading.setVisibility(View.GONE);
                        loadText.setVisibility(View.GONE);
                        OnClick();
                        adapter.notifyDataSetChanged();
                        String total_money = mainBean.getData().getTotal_money();
                        if (total_money.contains(".")) {
                            s1 = total_money.substring(0, total_money.indexOf("."));
                            s2 = total_money.substring(total_money.indexOf("."));
                        } else {
                            s1 = total_money;
                            s2 = ".00";
                        }
//                        mainBean.getData().getTotal_money() + "."
                        price.setText(s1);
                        price00.setText(s2);
                        if (mainBean.getData().getList().size() > 1) {
                            if (mainBean.getData().getList().get(1).getCoin_symbol().equals("ETH")) {
                                String addr = mainBean.getData().getList().get(1).getAddr().substring(0, 10) + "..." + mainBean.getData().getList().get(1).getAddr().substring(mainBean.getData().getList().get(1).getAddr().length() - 8, mainBean.getData().getList().get(1).getAddr().length());
                                SharedPrefsUtil.putValue(getActivity(), "wallet", "eth_addr", addr);
                                SharedPrefsUtil.putValue(getActivity(), "wallet", "eth_addrs", mainBean.getData().getList().get(1).getAddr());
                                eth_addrs = mainBean.getData().getList().get(1).getAddr();
                                ewm.setText(addr);
                            }
                        }
                        smart.finishRefresh();
                    } else {
                        initData();
                    }
                } else {
                    if (mainBean.getCode() == 401) {
                        Toast.makeText(getActivity(), getString(R.string.other_phone), Toast.LENGTH_SHORT).show();
                        Intent mIntent=new Intent(getActivity(), RecoveryActivity.class);
                        startActivity(mIntent);
                        getActivity().finish();
                    } else {
                        smart.finishRefresh();
                        loading.clearAnimation();
                        loadError.setVisibility(View.VISIBLE);
                        loading.setVisibility(View.GONE);
                        loadText.setVisibility(View.GONE);
                        mList.setVisibility(View.GONE);
                    }
                }
                SharedPrefsUtil.putValue(getActivity(), "wallet", "codes", 1);
            }

            @Override
            public void onFailure(String error) {
                smart.finishRefresh();
                loading.clearAnimation();
                loadError.setVisibility(View.VISIBLE);
                loading.setVisibility(View.GONE);
                loadText.setVisibility(View.GONE);
                mList.setVisibility(View.GONE);
                SharedPrefsUtil.putValue(getActivity(), "wallet", "codes", 1);
//                toast(error);
            }
        });

        langage = SharedPrefsUtil.getValue(getActivity(), "wallet", "langage", Api.chinese);
        reqequestManager.httpPost(Api.BaseUrl + Api.User_Information, Api.getUserInformation(token, langage), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Gson gson = new Gson();
                TokenBean json = gson.fromJson(Response, TokenBean.class);
                SharedPrefsUtil.putValue(getActivity(), "wallet", "head_img", json.getData().getHead_portrait());
            }

            @Override
            public void onFailure(String error) {
                Log.e("TAG", error);
            }
        });
    }


    public void initAdapter() {
        adapter = new AssetListAdapter(getActivity(), dataBeanList);
        mList.setAdapter(adapter);
    }


    @Override
    public int getLayoutResource() {
        return R.layout.fragment_home;
    }


    @OnClick({R.id.skm, R.id.insert})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.skm:
                if (mainBean != null) {
                    if (mainBean.getData() != null && eth_addrs != null) {
                        Intent intent = new Intent(getActivity(), ReceivableActivity.class);
                        intent.putExtra("datas", eth_addrs);
                        startActivity(intent);
                    }
                }
                break;
            case R.id.insert:
                Intent intent = new Intent(getActivity(), AddCurrencyActivity.class);
                startActivity(intent);
                break;
        }

    }

    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    private void checkUpgrade(final String downloadUrl, int value) {
        view = View.inflate(getActivity(), R.layout.popup_update, null);
        final Button bt_think_again = (Button) view.findViewById(R.id.bt_think_again);
        final Button bt_to_update = (Button) view.findViewById(R.id.bt_to_update);
        final RelativeLayout iv_top = (RelativeLayout) view.findViewById(R.id.iv_top);
        final LinearLayout ib_updata = (LinearLayout) view.findViewById(R.id.ll_updata);
        final TextView tv_updata = (TextView) view.findViewById(R.id.tv_updata);
        final TextView line = (TextView) view.findViewById(R.id.line);
        final LinearLayout ll_select_updata = (LinearLayout) view.findViewById(R.id.ll_select_updata);
        final RelativeLayout rl_force_updata = (RelativeLayout) view.findViewById(R.id.rl_force_updata);

        if (value == 0) {
            //强制更新
            line.setVisibility(View.GONE);
            ll_select_updata.setVisibility(View.GONE);
            rl_force_updata.setVisibility(View.VISIBLE);
        } else {
            //选择更新
            line.setVisibility(View.VISIBLE);
            ll_select_updata.setVisibility(View.VISIBLE);
            rl_force_updata.setVisibility(View.GONE);
        }


        //logo加圆角
        Bitmap bmBitmap = AboutActivity.getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.bg_qbbbgx));
        iv_top.setBackground(new BitmapDrawable(bmBitmap));


//        tv_updata.setText(mes);//最新版本备注
//        tv_new.setText(getString(R.string.TheCurrentVersion).toString()+":1.0.0");
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(fl_activity, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(getActivity(), 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(getActivity(), 1.0f);
                    }
                });

                //再想想
                bt_think_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });

                //去更新
                bt_to_update.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri uri = Uri.parse(downloadUrl);
                        intent.setData(uri);
                        startActivity(intent);
                        window.dismiss();
                    }
                });

                //立即更新
                ib_updata.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri uri = Uri.parse(downloadUrl);
                        intent.setData(uri);
                        startActivity(intent);
                        window.dismiss();

                    }
                });
            }
        });

    }


}